package com.msb.mall.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.msb.common.constant.ProductConstant;
import com.msb.mall.product.dao.AttrAttrgroupRelationDao;
import com.msb.mall.product.dao.AttrGroupDao;
import com.msb.mall.product.entity.AttrAttrgroupRelationEntity;
import com.msb.mall.product.entity.AttrGroupEntity;
import com.msb.mall.product.entity.CategoryEntity;
import com.msb.mall.product.service.*;
import com.msb.mall.product.vo.AttrGroupRelationVO;
import com.msb.mall.product.vo.AttrResponseVO;
import com.msb.mall.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.msb.common.utils.PageUtils;
import com.msb.common.utils.Query;

import com.msb.mall.product.dao.AttrDao;
import com.msb.mall.product.entity.AttrEntity;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;
    @Autowired
    AttrGroupService attrGroupService;
    @Autowired
    CategoryService categoryService;

    @Autowired
    AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Autowired
    AttrGroupDao attrGroupDao;


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttrVo(AttrVO attrVo) {
        //保存规格参数的正常信息
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attrVo, attrEntity);
        this.save(attrEntity);
        //保存规格参数和属性组的对应信息
        if (attrVo.getAttrGroupId() != null && attrVo.getAttrType() == ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attrVo.getAttrGroupId());
            //将关联的数据存储到对应的表结构中
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);

        }
    }

    @Override
    public PageUtils queryBasePage(Map<String, Object> params, Long catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        //根据类别编号查询
        wrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEum.ATTR_TYPE_SALE.getCode());
        if (catelogId != 0) {
            wrapper.eq("catelog_id", catelogId);
        }
        //根据key模糊查询
        String key = (String) params.get("key");

        if (!StringUtils.isEmpty("key")) {
            wrapper.and(
                    (w) -> {
                        w.eq("attr_id", key).or().like("attr_name", key);
                    }
            );

        }
        //分页查询
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        //4.关联类别名称和属性组名称数据
        List<AttrEntity> records = page.getRecords();

        List<AttrResponseVO> list = records.stream().map(
                (attrEntity) -> {
                    AttrResponseVO reponseVo = new AttrResponseVO();
                    BeanUtils.copyProperties(attrEntity, reponseVo);
                    //查询对应类别的名称
                    CategoryEntity categoryEntity = categoryService.getById(attrEntity.getCatelogId());
                    if (categoryEntity != null) {
                        reponseVo.setCatelogName(categoryEntity.getName());
                    }
                    if ("base".equalsIgnoreCase(attrType)) {
                        //设置属性组名称
                        //去关联表中找到对应的属性组id
                        AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                        entity.setAttrId(attrEntity.getAttrId());

                        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
                        if (attrAttrgroupRelationEntity != null && attrAttrgroupRelationEntity.getAttrGroupId() != null) {
                            //获取属性组id,然后根据属性组id查询名称
                            AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrAttrgroupRelationEntity.getAttrGroupId());
                            reponseVo.setGroupName(attrGroupEntity.getAttrGroupName());

                        }
                    }

                    return reponseVo;
                }
        ).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }

    /**
     * 根据规格参数查询对应的详细信息
     * 规格参数的具体信息
     * 关联的属性组信息
     * 关联的类别信息
     *
     * @param attrId
     * @return
     */
    @Override
    public AttrResponseVO getAttrInfo(Long attrId) {
        //声明返回的对象
        AttrResponseVO responseVo = new AttrResponseVO();
        //根据id查询规格参数的基本信息
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, responseVo);

        //查询关联的属性组信息
        if (attrEntity.getAttrType() == ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode()) {
            AttrAttrgroupRelationEntity relationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
            if (relationEntity != null) {
                AttrGroupEntity groupEntity = attrGroupService.getById(relationEntity.getAttrGroupId());
                responseVo.setAttrGroupId(groupEntity.getAttrGroupId());
                if (groupEntity != null) {
                    responseVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }

            //查询关联的类别信息
            Long catelogId = attrEntity.getCatelogId();
            Long[] catelogPath = categoryService.findCatelogPath(catelogId);
            responseVo.setCatelogPath(catelogPath);
            System.out.println("catelogPath 输出为" + catelogPath);
            CategoryEntity categoryEntity = categoryService.getById(catelogId);
            if (categoryEntity != null) {
                responseVo.setCatelogName(categoryEntity.getName());
            }

        }

        return responseVo;
    }

    @Override
    public void updateBaseAttr(AttrVO attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        //更新基础数据
        this.updateById(entity);
        if (attr.getAttrType() == ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode()) {
            //修改分组关联的关系
            AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            //判断是否存在对应的数据
            Integer count = Math.toIntExact(attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId())));
            if (count > 0) {
                //说明有更新,直接更新
                attrAttrgroupRelationDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            } else {
                //说明没有记录，直接插入
                attrAttrgroupRelationDao.insert(relationEntity);
            }
        }
    }

    @Transactional
    @Override
    public void removeByIdsDetails(Long[] attrIds) {
        //删除关联数据
        for (Long attrId : attrIds) {
            AttrEntity byId = getById(attrId);
//            System.out.println("数据是："+attrId+"---"+byId.getAttrType()+"---"+ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode());
            if (byId != null && byId.getAttrType() == ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode()) {
                System.out.println("数据是1：" + attrId);
                //删除关联属性中间表的信息
                attrAttrgroupRelationDao.delete(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
                System.out.println("数据是2：" + attrId);
            }
        }
        //删除属性表中的数据
        this.removeByIds(Arrays.asList(attrIds));

    }

    /**
     * 根据属性组编号查询对应的基本信息
     *
     * @param attrgroupId
     * @return
     */
    @Override
    public List<AttrEntity> getRelation(Long attrgroupId) {
        //根据属性编号 从属性组和基本信息的关联表中查询出对应的属性信息
        List<AttrAttrgroupRelationEntity> list = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        //根据属性id数组获取对应的详细信息
        List<AttrEntity> attrEntities = list.stream()
                .map((entity) -> {
                    return this.getById(entity.getAttrId());
                })
                .filter((entity) -> {
                    return entity != null;
                })
                .collect(Collectors.toList());

        return attrEntities;
    }

    /**
     * 解除属性组和基本属性的关联关系
     * 删除 attr_attrgroup_relation 数据
     *
     * @param vos
     */
    @Override
    public void deleteRelation(AttrGroupRelationVO[] vos) {
        List<AttrAttrgroupRelationEntity> list =
                Arrays.asList(vos)
                        .stream()
                        .map((item) -> {
                            AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                            BeanUtils.copyProperties(item, entity);
                            return entity;
                        })
                        .collect(Collectors.toList());
        //批量的删除关联数据
        attrAttrgroupRelationDao.removeBatchRelation(list);
    }

    /**
     * 根据属性组的id
     * 查询出未被关联的属性信息
     * 1.查询出所有的属性信息
     * 找到的属性信息，必须是和属性组类别相同的属性
     * 2.查询出当前属性组的关联信息
     * 3.1排除2 属性信息
     *
     * @param params
     * @param attrgroupId
     * @return
     */
    @Override
    public PageUtils getNoRelation(Map<String, Object> params, Long attrgroupId) {
        //查询当前属性组所在的类别编号
        AttrGroupEntity attrGroupEntity = attrGroupService.getById(attrgroupId);
        //获取对应的分类id
        Long catelogId = attrGroupEntity.getCatelogId();
        //当前分组只能关联自己所属类别下的其它分组没有关联的信息
        //所有的关联的数据查询出来
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        //获取属性组的编号集合
        List<Long> groupIds = group.stream().map(
                (g) -> {
                    return g.getAttrGroupId();
                }
        ).collect(Collectors.toList());
        List<AttrAttrgroupRelationEntity> relationEntities = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", groupIds));
        List<Object> attrIds = relationEntities.stream().map((m) -> {
                    return m.getAttrId();
                }
        ).collect(Collectors.toList());
        //根据类别编号查询所有的属性信息并排除掉上面的属性信息
        //最终查询结果
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEum.ATTR_TYPE_BASE.getCode());

        //添加排查的条件
        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        //根据key的查询操作
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        //查询对应的相关信息分页封装
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        return new PageUtils(page);
    }


}
